﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Linq;

using $prjsn$.Common;
using $prjsn$.Common.Validation;
using $prjsn$.Entity.Services;

namespace $safeprojectname$.Services
{
    public class AttachmentValidator : ValidatorBase<Attachment>
    {
        #region members

        /// <summary>Not more then 200 KB</summary>
        private const int MaxImageSize = 200000;

        /// <summary>Not more then 10 MB</summary>
        private const int MaxZipSize = 10000000;

        #endregion members

        protected override void Init(RuleCollection<Attachment> rules)
        {
            // string
            rules.For(entity => entity.Name).RequireLengthBetween(2, 250);

            // references
            rules.Require(entity => entity.Article);
            rules.Require(entity => entity.InputStream).BreakOnError();
            rules.Require(entity => entity.ContentType).BreakOnError();

            rules.Assure(CheckContentType);
            rules.Assure(CheckInputStreamLength);
        }

        #region Check

        protected virtual ValidationResult CheckContentType(Attachment entity, out ValidationMessage message)
        {
            message = null;
            if (entity.ContentType.IsImage
                || entity.ContentType.IsZip)
            {
                return ValidationResult.IsValid;
            }
            message = new ValidationMessage("ProvidedFileWasOfProhibitedContentType {0} {1}")
            {
                entity.Name,
                entity.InputStream.Length,
            };
            return ValidationResult.Error;
        }

        protected virtual ValidationResult CheckInputStreamLength(Attachment entity, out ValidationMessage message)
        {
            message = null;
            var size = entity.InputStream.Length;

            if (entity.ContentType.IsImage
                && size > MaxImageSize)
            {
                message = new ValidationMessage("ProvidedFileWasToLarge {0} {1}")
                {
                    size,
                    MaxImageSize,
                };
                return ValidationResult.Error;
            }
            if (entity.ContentType.IsZip
                && size > MaxZipSize)
            {
                message = new ValidationMessage("ProvidedFileWasToLarge {0} {1}")
                {
                    size,
                    MaxZipSize,
                };
                return ValidationResult.Error;
            }

            return ValidationResult.IsValid;
        }

        #endregion Check
    }
}